package com.sdy.dcsb.biz.util;

import com.sdy.dcsb.biz.constants.RedisConstants;
import com.sdy.dcsb.biz.model.EsbDictionary;
import com.sdy.dcsb.biz.model.EsbInboundParamDic;
import com.sdy.dcsb.biz.service.EsbDictionaryService;
import com.sdy.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 参数字典值配置缓存工具类
 * @author Snaky
 * @date 2020/5/12
 */
@Component
public class ParamDicCacheUtil {

    @Autowired
    private RedisService redisService;
    @Autowired
    private EsbDictionaryService dictionaryService;

    @SuppressWarnings("unchecked")
    public Map<String,String> getAllParamDic(){
        Map<String,String> paramDicMap = redisService.get(RedisConstants.CACHE_NAME_PARAM_DIC, Map.class);
        if(paramDicMap == null || paramDicMap.isEmpty()){
            List<EsbDictionary> paramDic = dictionaryService.getAllParamDic();
            if(paramDic == null || paramDic.isEmpty()){
                return null;
            }
            paramDicMap = paramDic.stream().collect(Collectors.toMap(EsbDictionary::getDicKey, EsbDictionary::getDicValue));
            redisService.set(RedisConstants.CACHE_NAME_PARAM_DIC, paramDicMap, RedisConstants.CACHE_VALIDITY_TIME);
        }

        return paramDicMap;
    }

    public void refreshCache(){
        List<EsbDictionary> paramDic = dictionaryService.getAllParamDic();
        if(paramDic == null || paramDic.isEmpty()){
            return ;
        }
        Map<String,String> paramDicMap = paramDic.stream().collect(Collectors.toMap(EsbDictionary::getDicKey, EsbDictionary::getDicValue));
        redisService.set(RedisConstants.CACHE_NAME_PARAM_DIC, paramDicMap, RedisConstants.CACHE_VALIDITY_TIME);
    }
}
